/**
 * @Description: 角色管理
 * @author 段大志
 * @date 2019/2/19 下午11:30
 */
import * as React from 'react';
import {
  Affix,
  BackTop,
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Icon,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Tooltip,
  Tree,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '@/components/ourslook/BaseForm';
import ETable from '@/components/ourslook/ETable';
import { getWebPath } from '../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../utils/uiUtils';
import styles from '../../utils/ourslook.less';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const TreeNode = Tree.TreeNode;
const Link = Tree.Link;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class Sysrole extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => `${index + 1}`,
    },
    { title: '角色ID', dataIndex: 'roleId', width: 80, align: 'left' },
    { title: '角色名称', dataIndex: 'roleName', width: 180 },
    { title: '备注', dataIndex: 'remark' },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'create_time',
      width: 180,
      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      dataIndex: '',
      width: 80,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('sys:role:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          {hasPermission('sys:role:save') && hasPermission('sys:role:update') && (
            <Divider type="vertical" />
          )}
          <a
            hidden={!hasPermission('sys:role:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.update" defaultMessage="修改" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Sysrole.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      menuList: [],
    };
  }

  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'nameOrId_LIke',
      label: '角色ID/角色名称',
      placeholder: '角色ID/角色名称',
    },
  ];

  componentDidMount() {
    this.requestList();
    this.getMenuTree();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: { status: 1, menuIdList: [] },
      showList: 2,
    });
  };

  update = () => {
    const { selectedIndexs, selectedRows, selectedIds } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].roleId);
  };

  view = () => {
    const { selectedIndexs, selectedRows, selectedIds } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].roleId);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const roleIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      roleIds.push(selectedRows[i].roleId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/sys/role/delete')}`, {
        method: 'POST',
        body: roleIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const role = Object.assign(this.state.editModel, this.editForm.props.form.getFieldsValue());

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = `${
          role.roleId == null ? '/sys/role/save' : '/sys/role/update'
        }?isAntDesign=true`;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: Object.assign(role),
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });

          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!role.roleId) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = roleId => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(getWebPath(`/sys/role/info/${roleId}`), {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });
      if (res && res.code === 0) {
        this.setState({
          editModel: res.role,
        });
      }
    });
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  getMenuTree = () => {
    requestPromise(`${getWebPath('/sys/menu/perms')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          menuList: res.menuList,
        });
      }
    });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('/sys/role/list')}`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <React.Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('sys:role:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>

            <Button
              type="primary"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('sys:role:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </React.Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="roleId"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              filtersSorterChange={this.filtersSorterChange}
              loading={this.state.loading}
              scroll={{ x: 900 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <Affix>
                <Button
                  onClick={() => {
                    this.editForm.props.form.resetFields();
                    this.setState({ showList: 1 });
                  }}
                >
                  <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                </Button>
              </Affix>
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                menuList={this.state.menuList}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
              <BackTop />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default Sysrole;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  //MenuType：0-->目录;1-->菜单;2-->按钮

  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    menuList: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    menuList: [],
  };

  constructor(props) {
    super(props);
    this.state = {
      checkedKeys: [],
      selectedKeys: [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    //这里设置选中的叶子节点，返回的是叶子节点和该叶子节点的所有父亲节点，这里过滤掉所有的父节点，只保留叶子节点
    const allIds = (nextProps.menuList || [])
      .filter(en => en.type === 2 || en.type === 1)
      .map(en => en.menuId);
    //const menuIdList = (nextProps.model.menuIdList || []).filter(en => allIds.includes(en));
    const menuIdList = nextProps.model.menuIdList || [];

    this.state = {
      checkedKeys: menuIdList,
    };
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  //转换菜单数组-->合适的数据
  menuConversionList = () => {
    //查询根菜单列表
    const rootMenus = this.menuFindByParent(0);
    //递归获取子菜单
    this.menuFindTreeList(rootMenus);
    //外层包裹一下
    return [{ title: '平台权限', key: '0', value: '', children: rootMenus }];
  };

  menuFindByParent = parentId => {
    const rootMenus = this.props.menuList
      .filter(en => en.parentId === parentId)
      .map(en => ({
        title: en.name,
        key: en.menuId,
        value: en.menuId,
        url: en.url,
        type: en.type,
      }));
    return rootMenus || [];
  };

  menuFindTreeList = menus => {
    const subMenuList = [];
    for (let i = 0; i < menus.length; i += 1) {
      const menu = menus[i];
      if (menu.type === 0 || menu.type === 1) {
        menu.children = this.menuFindTreeList(this.menuFindByParent(menu.key));
      }
      subMenuList.push(menu);
    }
    return subMenuList;
  };

  treeOnCheck = checkedKeys => {
    this.setState({ checkedKeys });
    this.props.model.menuIdList = checkedKeys;
  };

  treeOnSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
  };

  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} />;
    });

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    const inputRolenameRules =
      type !== 'view'
        ? [
            {
              required: true,
              message: '角色名称必填',
            },
            {
              whitespace: true,
              message: '不能包含空白符',
            },
            {
              min: 2,
              max: 30,
              message: '长度不在范围内',
            },
            rulesReg('roleName'),
            rulesRemote('POST', getWebPath('/sys/role/checkRole'), {
              roleNameOldValue: this.getPropsByKey('roleName'),
              userinfoIsAdd: type === 'add',
            }),
          ]
        : [];
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="角色名称" {...formItemLayout}>
              {type === 'view'
                ? model.roleName
                : getFieldDecorator('roleName', {
                    initialValue: model.roleName,
                    rules: inputRolenameRules,
                  })(<Input type="text" maxLength={50} placeholder="角色名称" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="备注" {...formItemLayout}>
              {type === 'view'
                ? model.remark
                : getFieldDecorator('remark', {
                    initialValue: model.remark,
                    rules: [
                      {
                        min: 0,
                        max: 100,
                        message: '最长100个字符',
                      },
                    ],
                  })(<TextArea rows={3} maxLength={100} placeholder="备注" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="授权" {...formItemLayout}>
              <Tree
                checkable
                disabled={type === 'view'}
                defaultExpandAll
                onCheck={this.treeOnCheck}
                onSelect={this.treeOnSelect}
                checkedKeys={this.state.checkedKeys}
                selectedKeys={this.state.selectedKeys}
              >
                {this.renderTreeNodes(this.menuConversionList(this.props.menuList))}
              </Tree>
            </FormItem>
          </Col>
        </Row>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
